# -*- coding: utf-8 -*-
'''
Created on Jun 27, 2014

@author: GIANG NGUYEN
'''
import os
import sys
from urlparse import urljoin
import workerpool
# sys.path.append('C:/longhoanggiang/pyLib')
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
import lib
import logging
import sqlite3
import json
import re

logging.basicConfig(level=logging.DEBUG, format='%(levelname)s :: %(asctime)s :: %(message)s', datefmt='%d/%m/%Y %H:%M:%S')

crawlResult = {}

class CrawlJob(workerpool.Job):
    
    def __init__(self, callback, *args):
        self.callback = callback
        self.args = args
        
    def run(self):
        detail, key = self.callback(*self.args)
        global crawlResult
        crawlResult[key] = detail

class Crawler():
    
    cookieStr = ''
    
    def detectPages(self, treeNode):
        node = treeNode.xpath("//div[@class='bt_pagination']/div[@class='next']/following-sibling::*[1]/a")
        if len(node) == 0: return 1
        node = node[0]
        pageNum = int(float(lib.extractText("index(\d+)\.html", node.get('href'), 1, 0)))
        return pageNum
    
    def getChapters(self, url):
        data = []
        _url = url
        fakeChapter = raw_input("Use original chapter name (y/n): ")
        fakeChapter = True if fakeChapter == 'y' or fakeChapter == 'Y' else False
        response = lib.Web.load(_url)
        cookie = response.get_cookie()
        self.cookieStr = cookie
        tree = response.build_tree()
        if not re.search(r"/index\d+\.html", url):
            url = url.replace('.html', '/index1.html')
        maxPage = self.detectPages(tree)
        chapterCount = 1
        for page in range(1, maxPage + 1):
            if (page > 1):
                url = re.sub(r"index\d+\.html", "index{0}.html".format(page), url)
            tree = lib.Web.load(url, cookie=cookie).build_tree()
            xpathLst = ["//div[contains(., 'Danh sách chương')]/following-sibling::div[@class='danh_sach']/a".decode('utf-8'),
                         "//div[@class='danh_sach']/a"]
            for iXpath in xpathLst:
                items = tree.xpath(iXpath)
                for node in items:
                    link = node.get('href')
                    if link != '':
                        link = urljoin(url, link)
                    if link == '': continue
                    if (fakeChapter):
                        name = lib.stringify(node)
                        name = name.replace(' : ', ': ')
                        name = re.sub(r"--\d+--", '', name)
                    else:
                        name = "CHƯƠNG {0}".format(chapterCount)
                    data.append({'name': name, 'url': link, 'filename': lib.md5(link), 'parent': 0})
                    chapterCount += 1
                if len(items) > 0: break
        return data
    
    def getDetail(self, url):
        tree = lib.Web.load(url, cookie=self.cookieStr).build_tree()
        nodeContent = tree.xpath("//td[@id='ar-content-html' and @class='chi_tiet']")
        def handelImgTag(node):
            if node.tag == 'img':
                imgUrl = node.get('src')
                if imgUrl != '':
                    imgUrl = urljoin(url, imgUrl)
                    return "<img src=\"{0}\" width=\"100%\" />".format(imgUrl)
            return None
        content = lib.getText(nodeContent, paragraph_break=2, breakline_html=False, callback=handelImgTag).strip()
        content = content.replace("\n", "<br />")
        if type(content).__name__ == 'unicode':
            content = content.encode('utf-8')
        return content, lib.md5(url)
    
    def createTable(self, connection):
        cursor = connection.cursor()
        cursor.execute("CREATE TABLE IF NOT EXISTS udv_content('id' INTEGER PRIMARY KEY AUTOINCREMENT, 'hash' VARCHAR(32), 'name' VARCHAR(200), 'content' BLOB, 'is_header' INTEGER DEFAULT 0)")
        cursor.execute("CREATE INDEX IF NOT EXISTS hash_index ON udv_content(hash)")
        cursor.execute("CREATE INDEX IF NOT EXISTS id_index ON udv_content(id)")
        cursor.close()
    
    def getStory(self, url, output=None):
        if output == None:
            output = raw_input("Enter database name: ")
        path = "/longhoanggiang/database/{0}".format(output)
        if not os.path.exists(os.path.dirname(path)): os.makedirs(os.path.dirname(path), 0777)
        connection = sqlite3.connect(path)
        self.createTable(connection)
        
        chapters = self.getChapters(url)
        pool = workerpool.WorkerPool(size=1)
        
        for chapter in chapters:
            pool.put(CrawlJob(self.getDetail, chapter['url']))
        pool.shutdown()
        pool.wait()
        
        for chapter in chapters:
            name = chapter['name']
            detail = crawlResult[lib.md5(chapter['url'])]
            detail = "<h4 id='title'>{0}</h4>{1}".format(name, detail)
            cursor = connection.cursor()
            cursor.execute("INSERT INTO udv_content('name', 'content') VALUES(?, ?)", [name.decode('utf-8'), buffer(lib.compressStr(json.dumps(detail)))])
            cursor.close()
            print name
            print detail[0:300] if len(detail) >= 300 else detail
        
        connection.commit()
        connection.close()
        logging.info("saved database in {0}".format(path))
        
    
if __name__ == '__main__':
    
    c = Crawler()
    url = raw_input("Enter url: ")
    if url.startswith("http:"):
        c.getStory(url)
    else:
        logging.error("Inivalid URL")
    logging.info("Finished crawler")
    os._exit(1)
    